
#include "Base64Util.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/evp.h>

int base64_encode(unsigned char *in, int in_len , unsigned char *out, int *out_len){
    BIO *b64 , *bio_mem;
    BUF_MEM *bptr = NULL;
    int size = 0;

    if (in == NULL || out == NULL) {
		fprintf(stderr, "NULL params\n");
		return -1;
	}

    b64 = BIO_new(BIO_f_base64());
    bio_mem = BIO_new(BIO_s_mem());
    b64 = BIO_push(b64, bio_mem);
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);

    size = BIO_write(b64, in, in_len);
    if (size <= 0) {
		fprintf(stderr, "fail to BIO_write\n");
		return -1;
	}
    BIO_flush(b64);

    BIO_get_mem_ptr(b64, &bptr);
    *out_len = bptr->length;
    memcpy(out, bptr->data, bptr->length);

    BIO_free_all(b64);
    return 0;
}

int base64_decode(unsigned char *in, int in_len , unsigned char *out, int *out_len){
    BIO *b64, *bio_mem;
    int size = 0;

    if (in == NULL || out == NULL) {
		fprintf(stderr, "NULL params\n");
		return -1;
	}

    b64 = BIO_new(BIO_f_base64());
    bio_mem = BIO_new_mem_buf(in, in_len);
    b64 = BIO_push(b64, bio_mem);
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);

    size = BIO_read(b64, out, in_len);
    if (size <= 0) {
		fprintf(stderr, "fail to BIO_read\n");
		return -1;
	}
    out[size] = '\0';
    *out_len = size;

    BIO_free_all(b64);
    return 0;
}
